/**
 * 
 */
package tcp;

// import java.net.ServerSocket;
// import java.net.Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Observable;
import java.util.Observer;

import model.Model;

public class Server implements Observer {

	// Port
	private final int port = 8392;

	private Model model;

	public Server(Model model) {
		this.model = model;

		this.model.addObserver(this);
	}

	void test() throws IOException {
		System.out.println("Server gestartet");

		model.setNeueNachricht("Server gestartet");

		java.net.ServerSocket serverSocket = new java.net.ServerSocket(model.getPort());

		java.net.Socket client = warteAufAnmeldung(serverSocket);

		System.out.println("Angemeldet");

		model.setNeueNachricht("Client hat sich angemeldet");

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		for (int i = 0; i < 2;) { // Endlos

			schreibeNachricht(client, model.getSendeNachricht());

			// model.setNeueNachricht(leseNachricht(client));

			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	java.net.Socket warteAufAnmeldung(java.net.ServerSocket serverSocket)
			throws IOException {
		java.net.Socket socket = serverSocket.accept(); // blockiert, bis sich
														// ein Client angemeldet
														// hat
		return socket;
	}

	String leseNachricht(java.net.Socket socket) throws IOException {
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(socket.getInputStream()));
		char[] buffer = new char[255];
		int anzahlZeichen = bufferedReader.read(buffer, 0, 200); // blockiert
																	// bis
																	// Nachricht
																	// empfangen
		String nachricht = new String(buffer, 0, anzahlZeichen);
		return nachricht;
	}

	void schreibeNachricht(java.net.Socket socket, String nachricht)
			throws IOException {
		PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(
				socket.getOutputStream()));
		printWriter.print(nachricht);
		printWriter.flush();
	}

	@Override
	public void update(Observable o, Object arg) {

		if (o == model) {
			if (arg.equals("startServer")) {

				new Thread(new Runnable() {

					@Override
					public void run() {
						try {
							test();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}).start();

			}

		}

	}
}
